/**
 * 初始化整体客户图标
 */
define(function(){
    var ec=require('echarts');
    require('echarts/chart/line');
    require('echarts/chart/bar');
    var zrnumber = require('echarts/util/number');

    var myChart1 = ec.init(document.getElementById('addLossUser_num')); 
    var myChart2 = ec.init(document.getElementById('addLossUser_arpu'));

    var option_1 = {
        tooltip : {
            trigger: 'axis',
            formatter: tooltipFunc_1
        },
        legend: {
            data:['新增客户','存留客户','流失客户']
        },
        toolbox: {
            show : true,
            showTitle: true,
            orient:'vertical',
            feature : {
                mark : {show: true},
                magicType : {show: true, type: ['line', 'bar', 'stack', 'tiled']},
                restore : {show: true},
                saveAsImage : {show: true}
            }
        },
        calculable : true,
        grid: {
            y: 60,
            y2:15
        },
        dataZoom: {
           show: false,
           realtime : true
        },        
        xAxis: [{
            type: "category",
            position:'top',
            boundaryGap: true,
            data:[''],
            axisLabel:{formatter:function(value){
                return value.substr(0,4)+"-"+value.substr(4,2)+"-"+value.substr(6,2);
            }}
        }],
        yAxis: [
            {
                type: 'value'
            }
        ],
        series: []
    };

   var option_2 = {
        tooltip : {
            trigger: 'axis',
            formatter: tooltipFunc_2
        },
        legend: {
             y: 'bottom',
            data:['新增客户arpu','存留客户arpu','流失客户arpu']
        },
        toolbox: {
            show : false,
            showTitle: true,
            orient:'vertical',
            feature : {
                mark : {show: false},
                dataZoom : {show: true},
                magicType : {show: true, type: ['line', 'bar', 'stack', 'tiled']},
                restore : {show: true},
                saveAsImage : {show: true}
            }
        },
        calculable : true,
        grid: {          
            y: 35,
            y2:60
        },        
        dataZoom: {
            show: true,
             y: 0,
            height: 20,
            realtime : true,
            start: 90
        },        
        xAxis: [{
            type: "category",
            boundaryGap: true,
            data:[''],
            axisLabel:{formatter:function(value){
                return value.substr(0,4)+"-"+value.substr(4,2)+"-"+value.substr(6,2);
            }}
        }],
        yAxis: [
            {
                type: 'value'
            }
        ],
        series: [
            {
                name: '总人数',
                type: 'line',
                data:[]
            }
        ]
    };
    
var nameMap_0 = {"keep":"存留客户","add":"新增客户","flow":"流失客户"};
var nameMap_1 = {"keep":"存留客户arpu","add":"新增客户arpu","flow":"流失客户arpu"};

// 图例一一对应
    /**
     * 根据指标显示日数据
     * @param eventType= 2:第一次加载, 1:切换周，月刷新 
     */
    function show(eventType){
        var statType = $('#addLossUserOption').attr('statType');
        var cityName = $('#cityName').val(); 
        var businessName = $('#businessName').val();
        var cate = $('#cate_addLossUser').val();     
        var vipType = $('#vipType_addLossUser').val();  
        var proType = $('#proType_addLossUser').val();     
        
        myChart1.showLoading({ text: '正在努力的读取数据中...' });
        myChart2.showLoading({ text: '正在努力的读取数据中...' });
        $.ajax({
            url: '/dashboard/homePage/ajax/addLossUser',
            type: 'post',
            async: true,
            data:{"statType":statType,"businessName":businessName,"cate":cate,"vipType":vipType,"cityName":cityName,"proType":proType,"dataType":"chart"},
            dataType: 'json',
            success: function(data, textStatus) {
                //X轴时间
                option_1.xAxis[0].data = data.time;
                option_2.xAxis[0].data = data.time;
                //上图每条曲线
                var i = 0;
                var series_local = [];
      
                $.each(nameMap_0,function(colName,name){
                        series_local[i++] = {
                        name: name,
                        type: 'bar',
                        smooth: true,
                        stack: '总量',
                        symbol:'none',
                        itemStyle: {normal: {areaStyle: {type: 'default'}}},
                        'data': data.dataMap1[colName]
                        
                    };
                });
                option_1.series = series_local;

                //下图每条曲线
                i = 0;
                series_local = [];
                $.each(nameMap_1,function(colName,name){
                    series_local[i++] = {
                        name: name,
                        type: 'line',
                        smooth: true,
                        symbol:"none",
                        'data': data.dataMap2[colName]
                    };
                });
                option_2.series = series_local;        

                //区域缩放
                var datezoom_local={   
                    week:{start:(1-12/data.time.length)*100,end:100},
                    month:{start:0,end:100}
                };
                //少于31个点，全显
                if(data.time.length<31){
                    datezoom_local={
					    week:{start:0,end:100},
                        month:{start:0,end:100}
                    };
                }

                if(eventType == 1 || eventType == 2){
                    if('week' == statType){      
                        option_1.xAxis[0].axisLabel.formatter=function(value){ return value; } ;
                        option_2.xAxis[0].axisLabel.formatter=function(value){ return value; } ;
                    }else if('month' == statType){
                        option_1.xAxis[0].axisLabel.formatter=function(value){ return value.substr(0,4)+"年"+value.substr(4,2)+"月"; } ;
                        option_2.xAxis[0].axisLabel.formatter=function(value){ return value.substr(0,4)+"年"+value.substr(4,2)+"月"; } ;
                    }
                    option_1.dataZoom.start=datezoom_local[statType].start;
                    option_1.dataZoom.end=datezoom_local[statType].end;
                    option_2.dataZoom.start=datezoom_local[statType].start;
                    option_2.dataZoom.end=datezoom_local[statType].end;
                    if(eventType == 1 && myChart2.component.dataZoom){
                        myChart1.component.dataZoom.absoluteZoom(datezoom_local[statType]);
                        myChart2.component.dataZoom.absoluteZoom(datezoom_local[statType]);
                        option_2.dataZoom.show=true;
                    }else if(eventType == 2){
                       
                    }
                    myChart1.setOption(option_1,true);
                    myChart2.setOption(option_2,true);
                }
                // myChart.clear();
                myChart1.connect(myChart2);
                myChart2.connect(myChart1);
                myChart1.hideLoading();
                myChart2.hideLoading();
            },
            error : function() {
                myChart1.hideLoading();
                myChart2.hideLoading();
            }
        });
    }

    //图例选择事件
    var ecConfig = require('echarts/config');
    function eventClick(param){
        var click_date = '2014-01-01';
        if (typeof param.seriesIndex != 'undefined') {
            click_date = param.name;
        }else{
            return;
        }
        loadTableData(click_date);
    }
    myChart1.on(ecConfig.EVENT.CLICK, eventClick);
    myChart2.on(ecConfig.EVENT.CLICK, eventClick);

    //加载余额客户当天的数据，, 0:字符, 1:数字, 2:百分比
    var show_cols = {"product_type":0,"add#user_num":1,"add#user_num_chain":2,"add#arpu":1,"add#arpu_chain":2,
    "keep#user_num":1,"keep#user_num_chain":2,"keep#arpu":1,"keep#arpu_chain":2,
    "flow#user_num":1,"flow#user_num_chain":2,"flow#arpu":1,"flow#arpu_chain":2};
    var mapdata={"jingzhun":0,"zhiding":1,"zhineng":2};
    var nameMap={"jingzhun":"精准","zhiding":"置顶","zhineng":"智能"};
   
    function loadTableData(stat_date){  
        var statType = $('#addLossUserOption').attr('statType');
        var cityName = $('#cityName').val(); 
        var businessName = $('#businessName').val();
        var cate = $('#cate_addLossUser').val();     
        var vipType = $('#vipType_addLossUser').val();
        
        $.ajax({
            url: '/dashboard/homePage/ajax/addLossUser',
            type: 'post',
            async: true,
            data:{"statType":statType,"businessName":businessName,"cate":cate,"vipType":vipType,"cityName":cityName,"dateVal":stat_date,"dataType":"table"},
            dataType: 'json',
            success: function(data, textStatus) {
                var resultList = data.dataList;
                var res=[];
                res[0]={};res[1]={};res[2]={};
                $.each(resultList,function(i,vo){   
                       res[mapdata[vo['product_type']]]['product_type']=nameMap[vo['product_type']];
                        $.each(vo,function(col,colnumber){
                            if(col=="user_num"||col=="user_num_chain"||col=="arpu"||col=="arpu_chain")
                            {
                                 res[mapdata[vo['product_type']]][vo['user_type']+'#'+col]=colnumber;
                            }
                        });         
                });
                var htmlRows = "";
                $.each(res,function(i,vo){
                	if(res[i].product_type==null)
                	    return true;
                    htmlRows += "<tr>";
                    $.each(show_cols,function(col,colType){
                        switch(colType){
                            case 0:
                                htmlRows += "<td>";
                                htmlRows += vo[col];
                                htmlRows += "</td>";
                                break;
                            case 1:
                                htmlRows += "<td>";
                                if(vo[col]==null)
                                {
                                	htmlRows += '-';
                                }else{
									htmlRows += zrnumber.addCommas(vo[col]);
								}
                                htmlRows += "</td>";
                                break;
                            case 2:
                                if(vo[col]==null)
                                {
                                	htmlRows += "<td>-</td>";
                                }else{
									htmlRows += getRate(vo[col]);
								}                     
                                break;
                        }
                    });

                    htmlRows += "</tr>";
                });

                $('#addLossUserTable tr:gt(0)').remove();
                $('#addLossUserTable_date').text(stat_date.replace(/\-/g,"."));
                $('#addLossUserTable').append(htmlRows);
            },
            error : function() {
            }
        }); 
    }

    var all_Options = [option_1,option_2];
    function tooltipFunc_1(params, ticket, callback){
        return tooltipFunc(params, ticket, callback,0);
    }
    function tooltipFunc_2(params, ticket, callback){
        return tooltipFunc(params, ticket, callback,1);
    }
    //提示框
    function  tooltipFunc(params, ticket, callback,optionIndex){
        var dateVal = params[0].name;
        var curOption = all_Options[optionIndex];
        var index_current=getIndexByName(curOption.xAxis[0].data,dateVal);
        var seriename=curOption.series[0].name;
        var isarpu=seriename.indexOf("arpu")==-1?false:true;

        var result='<table class="table-center">';
        result+='<tr><td>'+dateVal+'</td><td>';
        var isStatDay = isDay(); 
        if(isStatDay)
            result += getWeekDay(dateVal);
        if(isarpu==false)
          result += '</td><td>占比</td>';
        else
           result += '</td>';
        if(isStatDay)
            result +="<td>日环比</td><td>周同比</td>";
        else if(isWeek())
            result += "<td>周环比</td>";
         else if(isMonth())
            result += "<td>月环比</td>";
        result += '</tr>';

        var total=0;

        $(params).each(function(index,para){
            if(para.data<0)
              total+=0-parseInt(para.data);
            else
              total+=parseInt(para.data);
        });

        $(params).each(function(index,para){
            var s=((parseInt(para.data)/total)*100).toFixed(2);
            if(s<0)
                s=0-s;
            if(isarpu==false)
                result+='<tr><td>'+para.seriesName+'</td><td>'+zrnumber.addCommas(para.data)+'</td><td>'+s+'%</td>';
            else
                result+='<tr><td>'+para.seriesName+'</td><td>'+zrnumber.addCommas(para.data)+'</td>';

            var seriesIndex = para.seriesIndex;
            var day_td="<td>--</td>";
            //日周月 环比(前一日周月)
            if(index_current-1>=0){
                var data_yesday = null;
                //上月
                if(isMonth()){
                    if(index_current-1>=0){
                        data_yesday= curOption.series[seriesIndex].data[index_current-1];
                    }
                }else{ 
                    data_yesday= curOption.series[seriesIndex].data[index_current-1];                
                }
                if(data_yesday != null){
                    var s=(((para.data/data_yesday)-1)*100).toFixed(2);
                    if(s>0){
                        day_td='<td style="color: orangered;">'+s+'%&#8593</td>';
                    }else{
                        day_td='<td style="color: greenyellow;">'+s+'%&#8595</td>';
                    }
                }
            }
            result += day_td;
            //周同比(日)
            if(isStatDay){
                var week_td='<td>--</td>';
                if(index_current-7>=0){
                    data_week= curOption.series[seriesIndex].data[index_current-7];
                    var s=(((para.data/data_week)-1)*100).toFixed(2);
                    if(s>0){
                        week_td='<td style="color: orangered;">'+s+'%&#8593</td>';
                    }else{
                        week_td='<td style="color: greenyellow;">'+s+'%&#8595</td>';
                    }
                }
                result += week_td;
            }
            result += '</tr>';
        });
        result+='</table>';
        return result;
    }           

   function formatShowDate(yyyymmdd){
        var statType = $('#addLossUserOption').attr('statType');
        if('day'==statType){
            return yyyymmdd;
        }else if('week'==statType){
            return yyyymmdd;
        }else if('month'==statType){
            return yyyymmdd.substr(0,4)+"年"+yyyymmdd.substr(5,2)+"月";
        }
    }

    function isDay(){
        var statType = $('#addLossUserOption').attr('statType');
        if('day'==statType){
            return true;
        }
        return false;
    }
    
     function isWeek(){
         var statType = $('#addLossUserOption').attr('statType');
        if('week'==statType){
            return true;
        }
        return false;
    }

    function isMonth(){
        var statType = $('#addLossUserOption').attr('statType');
        if('month'==statType){
            return true;
        }
        return false;
    }

    var zrUtil = require('zrender/tool/util');
    // console.log(zrUtil);


    var xAxis_show;     // X轴所显示的时间区间
    var legend_SelectedMap={};  //需要记忆图例的选择状态
    function hideDataZoom(){
        var legend_SelectedMap_1=zrUtil.clone(myChart1.component.legend.getSelectedMap());
        var legend_SelectedMap_2=zrUtil.clone(myChart2.component.legend.getSelectedMap());
        legend_SelectedMap = zrUtil.merge(legend_SelectedMap_1, legend_SelectedMap_2, true);
        xAxis_show=zrUtil.clone(myChart1.component.dataZoom.option.xAxis[0].data);    //记忆缩放
        option_2.dataZoom.show=false;

        myChart1.setOption(option_1,false);
        myChart2.setOption(option_2,false);
    }

    //设置缩放区间
    function setDataZoom (startDate,endDate) {
        var xAxisLength = option_2.xAxis[0].data.length;
        var index_start=getIndexByName(option_2.xAxis[0].data,startDate) + 1;
        var index_end=getIndexByName(option_2.xAxis[0].data,endDate) + 1;
        var zoomRange = {start:index_start/xAxisLength*100,end:index_end/xAxisLength*100};
        myChart2.component.dataZoom.absoluteZoom(zoomRange);
    }


    function getIndexByName(data,name) {
        var dataLength = data.length;
        for (var i = 0; i < dataLength; i++) {
            if (data[i] == name || typeof data[i].value != 'undefined' && data[i].value == name) {
                return i;
            }
        }
        return -1;
    }

    function formatTime(time){
        return time;
    }

    function getShowDays(){
        return xAxis_show;
    }

    function getAllDays(){
        return option_2.xAxis.data||option_2.xAxis[0].data;
    }
    var EC={
        show:show,
        resize:function(){myChart1.resize();myChart2.resize();},
        hideDataZoom:hideDataZoom,
        getShowDays:getShowDays,
        getAllDays:getAllDays    
    };
    
    //绑定书刷新按钮点击事件
    $("#refresh_addLossUser_btn").click(function(){
        var type = 2;      
        EC.show(type);
    });

    $(":button.btn_addLossUser[statType]").click(function(){
        changeDateGrp(this);
        EC.show(1);
    });

    return EC;
});

